#include "TopographyManager.h"
#include "config.h"
#include "Topography.h"
#include "Ground.h"

TopographyManager::TopographyManager()
{
}

TopographyManager::~TopographyManager()
{
}

void TopographyManager::init(CCNode * pParent, b2World * world)
{
  this->pParent = pParent;
  restart(world);
}

void TopographyManager::update(b2Body * body)
{
  float screenStart = body->GetPosition().x- PLAYER_POS_OFFSET_X;
  float screenEnd = screenStart + WORLD_WIDTH;
  Topography * pT = this->topographyDeque.front();
  while (pT && pT->getEndPoint().x < screenStart)
  {
    this->pParent->removeChild(pT);
    this->topographyDeque.pop_front();
    pT = this->topographyDeque.front();
  }
  pT = this->topographyDeque.back();
  while (pT && pT->getEndPoint().x < screenEnd)
  {
    pT = pT->createNext();
    this->topographyDeque.push_back(pT);
  }
}

void TopographyManager::restart(b2World * world)
{
  while (this->topographyDeque.size())
  {
    Topography * pT = this->topographyDeque.front();
    this->pParent->removeChild(pT);
    this->topographyDeque.pop_front();
  }
  this->topographyDeque.push_back(Ground::create(this->pParent, world, ccp(0, PLAYER_POS_OFFSET_Y)));
}
